<template>
  <div class="myBetRecord hideScrollBar">
    <ClientOnly>
      <!-- 导航 -->
      <NavBar
        :title="t('lotteryMoney.wdxz')"
        isFixed
        :isShadow="false"
        @getNavBarHeight="(h) => (pageData.navBarHeight = h)"
      />
      <!-- 工具栏 -->
      <div class="tool items-center">
        <!-- 时间展示 -->
        <div
          class="items-center tool-time"
          @click="pageData.isSHowPicker = true"
        >
          <div>{{ selectTime }}</div>
          <div style="width: 10px; height: 10px; margin: 0 5px">
            <Images src="/image/assetDetails/date-jt.svg" />
          </div>
        </div>
        <!-- 三个快捷菜单 -->
        <div class="items-center tool-menu">
          <div
            class="tool-menu-btn"
            :class="{ 'tool-menu-activity': pageData.menuType == 1 }"
            @click.stop="menuTypeChange(1)"
          >
            {{ t("lotteryMoney.xzjl") }}
          </div>
          <div
            class="tool-menu-btn"
            :class="{ 'tool-menu-activity': pageData.menuType == 2 }"
            @click.stop="menuTypeChange(2)"
          >
            {{ t("lotteryMoney.zjjl") }}
          </div>
        </div>
      </div>
      <!-- 内容部分 -->
      <div
        class="contentview hideScrollBar"
        :style="{
          height: `calc(100vh - ${pageData.navBarHeight}px - 44px)`,
        }"
        :class="{
          'contentview-notdata-bg':
            !pageData.loading && pageData.list.length === 0,
        }"
      >
        <!-- 暂无内容 -->
        <div
          v-if="!pageData.loading && pageData.list.length === 0"
          class="contentview-notdata items-center"
        >
          <img class="contentview-notdata-img" src="/image/notdate-icon.png" />
          <div class="contentview-notdata-desc">{{ t("mvp.other.zwnr") }}</div>
        </div>
        <!-- 列表 -->
        <van-list
          v-else
          v-model:loading="pageData.loading"
          :finished="pageData.finished"
          :finished-text="t('mvp.other.text4')"
          :loading-text="t('mvp.other.text11')"
          @load="onLoadList"
        >
          <!-- 列表 -->
          <MybetCell
            style="position: relative; z-index: 9"
            :list="pageData.list"
            :cellType="pageData.menuType"
          ></MybetCell>
        </van-list>
      </div>
      <!-- 圆角弹窗（底部） -->
      <DatePicker
        v-model:show="pageData.isSHowPicker"
        @confirm="confirmTime"
      ></DatePicker>
    </ClientOnly>
  </div>
</template>
<script setup name="myBetRecord">
import { navigateI18nTo } from "@/utils";
import { useGlobalStore } from "~~/store/global";
import { getMyBettingRecord, getMyPrizeRecord } from "../../api/lottery";
import { useDateFormat } from "@vueuse/core";
import DatePicker from "../../components/assetDetails/date-picker.vue";
import MybetCell from "../../components/lotterymoney/mybet-cell.vue";

const { t } = useI18n();
// const route = useRoute();
// console.log("页面参数:", route.query);

// definePageMeta({
//   keepalive: true,
// });

const globalStore = useGlobalStore();
// 如果没有登录-直接跳转登录页面
if (!globalStore.$state.token && process.client) {
  bridge.onAppLogin();
}

// firebase埋点
const firebase = useInitFirebase(); // 初始化firebase

// 页面属性
const pageData = reactive({
  isSHowPicker: false,
  navBarHeight: 0,
  // 上拉加载属性
  loading: false,
  finished: false,
  prefixs: [], // 分类标识
  list: [],
  pageNum: 0,
  total: 0,
  // 筛选项
  startTime: 0,
  endTime: 0,
  menuType: 1, // 1： 下注记录 2： 中奖记录
  selectType: 4, // -1：没有选择  1： 按月  2：按天 3：上个月 4：近3 个月 5：开始时间  6：结束时间
});

const selectTime = computed(() => {
  if (pageData.selectType === 1) {
    return useDateFormat(pageData.startTime, "YYYY.M").value;
  } else if (pageData.selectType === 3) {
    return t("mvp.incomeStatement.sy");
  } else if (pageData.selectType === 4) {
    return t("mvp.zj90t");
  } else if (pageData.selectType === 5 || pageData.selectType === 6) {
    return `${useDateFormat(pageData.startTime, "YYYY.M.D").value}-${
      useDateFormat(pageData.endTime, "YYYY.M.D").value
    }`;
  } else {
    return t("mvp.incomeStatement.default");
  }
});

/**
 * @description: 上啦加载
 * @param {*} isRetry 重试一次
 * @author: zhj1214
 */
const onLoadList = (isRetry) => {
  pageData.pageNum += 1;
  getMyBettingRecordRequest((isAdd) => {
    if (!isAdd) {
      pageData.pageNum -= 1;
      if (!isRetry) {
        setTimeout(() => {
          onLoadList(true);
        }, 3000);
      }
    }
  });
};

// 当前数据总和,用来判断是否还需要上啦加载
const recordsTotal = computed(() => {
  let total = 0;
  pageData.list.forEach((yf) => {
    if (yf.list) {
      total += yf.list.length;
    }
  });
  return total;
});

// 获取列表数据
const getMyBettingRecordRequest = async (call) => {
  pageData.loading = true;
  let api = pageData.menuType == 1 ? getMyBettingRecord : getMyPrizeRecord;
  const res = await api({
    beginTime: pageData.startTime,
    endTime: pageData.endTime,
    pageNum: pageData.pageNum,
    pageSize: 20,
  });
  pageData.loading = false;

  // console.log("--获取列表数据--", res);
  if (res) {
    if (res.records && res.records.length > 0) {
      res.records.forEach((e) => {
        // e.drawType = 3
        // 1. 加工数据
        const t = useDateFormat(
          Number(e.drawTime || e.sendTime),
          "YYYY-MM-DD HH:mm:ss"
        );
        e.timeStr = t.value;
        // 2.分类数据
        const prefix = t.value.substring(0, 7);
        if (pageData.prefixs.includes(prefix)) {
          pageData.list.forEach((b) => {
            if (b.months === prefix) {
              b.list.push(e);
              if (e.isAdd) {
                b.income = Number(b.income) + Number(e.changeAmount);
              } else {
                b.expenses = Number(b.expenses) - Number(e.changeAmount);
              }
            }
          });
        } else {
          pageData.prefixs.push(prefix);
          pageData.list.push({
            months: prefix,
            list: [e],
          });
        }
        return e;
      });
    }

    // console.log("--分类后的数据：", pageData.list);
    // pageData.list = pageData.list.concat(arr);
    pageData.total = res.total;
    if (recordsTotal.value >= res.total) {
      pageData.finished = true;
    } else {
      pageData.finished = false;
    }
    if (res.records && res.records.length > 0) {
      call && call(true);
    } else {
      call && call(false);
    }
  } else {
    pageData.finished = true;
    call && call(false);
  }
};

onMounted(() => {
  // 1. 埋点访问
  firebase?.logEvent("BDC_H5_lottery_MyBet_PUV");
  // 2. 默认三个月数据
  const curt = new Date();
  // pageData.startTime = curt.getTime() - 3 * 30 * 24 * 60 * 60 * 1000;
  const begin = new Date(curt.getTime() - 3 * 30 * 24 * 60 * 60 * 1000);
  pageData.startTime = new Date(
    `${begin.getFullYear()}/${begin.getMonth() + 1}/${begin.getDate()} 00:00:00`
  ).getTime();
  pageData.endTime = curt.getTime();

  // 3. 请求数据
  onLoadList();
});
// 全部、收入、支出
const menuTypeChange = (val) => {
  // 1. 是否重置数据
  if (val !== pageData.menuType) {
    pageData.list = [];
    pageData.prefixs = [];
    pageData.finished = false;
  } else {
    return;
  }
  // 2. 赋值、请求新数据
  pageData.pageNum = 1;
  pageData.menuType = val;
  getMyBettingRecordRequest();
};
// 弹窗确认筛选时间
const confirmTime = ({ start, end, type }) => {
  // 1. 如果没有选择时间，则不做任何改变
  if (start === 0 || end === 0) return;
  // 2. 赋值属性
  pageData.list = [];
  pageData.prefixs = [];
  pageData.startTime = start;
  pageData.endTime = end;
  pageData.pageNum = 1;
  pageData.selectType = type;
  pageData.finished = false;
  // 3. 请求接口
  getMyBettingRecordRequest();
};
</script>
<style lang="scss" scoped>
.myBetRecord {
  min-height: 100vh;
  background-color: #f4f5f7;

  .tool {
    width: 100vw;
    height: 42 * 2px;
    background-color: #fff;

    &-time {
      padding-left: 8 * 2px;
      font-size: 12 * 2px;
      color: #007bff;
      font-weight: 650;
    }
    &-menu {
      flex: 1;
      border-left: 1 * 2px solid #f5f5f5;
      padding-left: 5 * 2px;
      font-weight: 600;
      &-btn {
        text-wrap: nowrap;
        white-space: nowrap;
        font-size: 12 * 2px;
        color: #141924;
        padding: 6px 8 * 2px;
      }
      &-activity {
        color: #007bff !important;
        background-color: #ecf5ff !important;
        border-radius: 4 * 2px;
      }
    }
  }
  .contentview {
    padding-bottom: var(--safe-area-inset-bottom);
    background-color: #f4f5f7;
    overflow-y: scroll;
    position: relative;
    &-header {
      padding: 16 * 2px 16 * 2px 0 16 * 2px;
      // margin-top: 10 * 2px;
      position: relative;
      top: 20px;
      height: 78 * 2px;
      z-index: 8;
      &-text {
        margin-top: 10 * 2px;
        color: #141924;
        font-size: 15 * 2px;
        font-weight: 590;
        letter-spacing: -0.8px;
      }
      &-left {
        position: relative;
        &-text {
          color: #141924;
          font-size: 13 * 2px;
          font-weight: 590;
          letter-spacing: -0.8px;
        }
        &-img {
          width: 16 * 2px;
          height: 16 * 2px;
          margin-right: 5 * 2px;
        }
      }
      &-img {
        border-top-right-radius: 12 * 2px;
        border-top-left-radius: 12 * 2px;
        position: absolute;
        top: 0;
        left: 0;
        // height: 107 * 2px;
      }
    }
    &-notdata {
      justify-content: center;
      flex-direction: column;
      position: relative;
      top: 120 * 2px;
      &-img {
        width: 200 * 2px;
        height: 200 * 2px;
      }
      &-desc {
        margin-top: -35 * 2px;
        color: #999da7;
        font-size: 13 * 2px;
      }
      &-bg {
        background-color: #fff !important;
      }
    }
  }
}
</style>
